import React, { useState,useRef, useEffect} from "react";
import  Card from "./components/Card.js";
import CardContent from "./components/CardContent.js";
import Navbar from './components/Navbar';
import SearchMode from './SearchMode';
import { useNavigate } from 'react-router-dom'
import './Home.css';
import axios from "axios";
function News({content,score,date}){
  const navigate = useNavigate();
  const handleClick = (news) => {
    navigate('/chat',{state:news}); // 这里替换成你要跳转的路由路径
  };
 return <>
    <div className="news"  >
              <div className="news-item">
                <p>{content}</p>
                <p>{date}</p>
                <p>相关性得分:{score}</p>
                <button  className='custom_botton' onClick={() => handleClick(content)}>生成摘要</button>
              </div>
    </div>
</>;}
export default function HomePage() {
  const [hots,setHots] =useState([]);
  const navigate = useNavigate();
  const [searchMode, setSearchMode] = useState('keyword');
	const[news,setNews]=useState([]);
  const [isSent, setIsSent] = useState(false);//点击按钮重新渲染
	const inputRef = useRef(null);
  const [loading, setLoading] = useState(true);
  const handleSearchModeChange = (mode) => {
    setSearchMode(mode); // 更新当前选择的检索方式
  };
	const send = () => {
        if (inputRef.current.value === '') return;
        setLoading(true);
		axios({
			method: 'post',
			url: 'http://localhost:8080/consult/queryContent',
      headers: {
          'Authorization':  localStorage.getItem('token'),  // 示例：添加 Bearer token 作为认证头部
          'Content-Type': 'application/json'
      },
			data: {
			  query:inputRef.current.value,
        date:new Date().toISOString(),
        type:searchMode,
        userId:localStorage.getItem("userId")
			}
		  }).then((res) => {
            setIsSent(true); // 标记已发送，触发样式变化
            console.log('发送内容:', inputRef.current.value);
			// 判断响应结果
			if (res.data.resultCode === 200) {
        
        setNews(JSON.parse(res.data.data));
        setLoading(false);
			} else {
			  alert(res.data.message);
			}
		  }).catch((error) => {
			console.error("There was an error during the request!", error);
			alert("请重试");
		  });
	};
  useEffect(()=>{
    axios
    .get("http://localhost:8080/consult/getLastestNews", {
      params: {
        num:8
      },
      header:{
        'Authorization':  localStorage.getItem('token'),  // 示例：添加 Bearer token 作为认证头部
        'Content-Type': 'application/json'
      }
    })
    .then((res) => {
      console.log(res.data);
      console.log("数据类型："+typeof res.data);
      setHots(res.data);
    })
    .catch((err) => {
      console.error("获取新闻失败:", err);
    });
  },[]);
  return (
    <div>
      <Navbar />
      <div className="min-h-screen bg-gray-100 p-6 flex justify-center items-center">
      <div className="w-full max-w-screen-lg">
        {/* 页面头部 */}
        <header className="mb-6 text-center">
          <h1 className="text-4xl font-bold mb-2">新闻问答系统</h1>
          <p className="text-gray-600">基于检索增强生成模型的智能新闻问答平台</p>
        </header>

        {/* 提问区域 */}
        <div className="mb-6">
          <Card className="p-4 shadow-md mb-6">
            <CardContent className="flex gap-2">
            <SearchMode onModeChange={handleSearchModeChange} />
		        <input ref={inputRef} className='search-input' id="input" placeholder={'发送消息'}/>
			      <button  onClick={send}>🔍</button>
            </CardContent>
          </Card>
        </div>
        {loading ? (
          <section className="mb-6">
          <h2 className="text-2xl font-semibold mb-4">热点推荐</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {hots.map((item,index)=>(
              <Card><CardContent><li>{item.title}</li></CardContent></Card>
            ))}
          </div>
        </section>
        ) : (
        <div className="news-list">
          <h3>查询结果（共 {news.length} 条）</h3>
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {news.map((item) => (
              <News content={item.document} score={item.relevance_score} date={item.date}/>
            ))}
          </ul>
        </div>
      )}
      </div>
    </div>
    </div>
  );
}